package com.nike.amoeba.ui.frg

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.TimeUtils
import com.kingja.loadsir.core.LoadService
import com.nike.amoeba.R
import com.nike.amoeba.adapter.StockManageListAdapter
import com.nike.amoeba.adapter.TaskStockListAdapter
import com.nike.amoeba.api.UIHelper
import com.nike.amoeba.base.BaseFragment
import com.nike.amoeba.bean.DataBean
import com.nike.amoeba.bean.RfidStateBean
import com.nike.amoeba.bean.db.StockEpcBean
import com.nike.amoeba.bean.db.TaskStockListBean
import com.nike.amoeba.databinding.FTaskStockListBinding
import com.nike.amoeba.ext.SCAN_STATUS_QRCODE
import com.nike.amoeba.ext.SCAN_STATUS_SCAN
import com.nike.amoeba.ext.STOCK_EPC_ORDER_TYPE
import com.nike.amoeba.ext.init
import com.nike.amoeba.ext.loadServiceInit
import com.nike.amoeba.ext.setNbOnItemClickListener
import com.nike.amoeba.ext.showEmpty
import com.nike.amoeba.ext.showLoading
import com.nike.amoeba.mar.eventViewModel
import com.nike.amoeba.viewmodel.AssetModel
import com.nike.amoeba.viewmodel.RfidModel
import com.nike.amoeba.viewmodel.TaskStockListModel
import com.nike.amoeba.weight.recyclerview.SpaceItemDecoration
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import java.util.concurrent.locks.ReentrantLock

/**
 * @Author nike
 * @Date 2023/7/7 11:59
 * @Description    盘点库存列表
 */
class TaskStockListFrg : BaseFragment<TaskStockListModel, FTaskStockListBinding>(){

    val adapter: TaskStockListAdapter by lazy { TaskStockListAdapter(arrayListOf()) }

    lateinit var loadsir: LoadService<Any>

    val rfidModel: RfidModel by activityViewModels()

    val assetModel: AssetModel by activityViewModels()

    val lock = ReentrantLock()

    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            mViewModel.orderId.set(it.getString("orderId"))
            mViewModel.code.set(it.getString("code"))
        }
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        mViewModel.state.set(getString(R.string.start))
        mViewModel.save.set(getString(R.string.save))
        //状态页配置
        loadsir = loadServiceInit(mDatabind.swipeRefresh) {

        }

        //初始化recyclerView
        mDatabind.recyclerView.init(LinearLayoutManager(context), adapter).let {
            it.addItemDecoration(SpaceItemDecoration(ConvertUtils.dp2px(20f), ConvertUtils.dp2px(20f), true))
        }

        adapter.run {
            setNbOnItemClickListener{adapter, view, position ->
                val bean = adapter.data[position] as TaskStockListBean
                if (bean.ScanNum != 0){
                    UIHelper.startTaskStockEpcFrg(nav(), bean.RoNo!!, bean.BatchNo!!, mViewModel.code.get())
                }
            }

            setOnItemClickListener(object : TaskStockListAdapter.OnItemClickListener{
                override fun onDetailedClick(content: String?, AssetNo: String?) {
                    UIHelper.startStockTextFrg2(nav(), content, AssetNo)
                }
            })
        }

        mDatabind.swipeRefresh.isEnabled = false
        mDatabind.includeSearch.etText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                adapter!!.filter.filter(p0.toString())
            }

            override fun afterTextChanged(p0: Editable?) {
            }
        })

        mDatabind.includeSearch.ivQr.setOnClickListener {
            UIHelper.startZxingAct(STOCK_EPC_ORDER_TYPE)
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                setToolBarTitle(mViewModel.orderId.get()!!)
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                rfidModel.isOpen.value = false
                assetModel.epcData.value = null
                assetModel.epcUploadData.value = null
            }

            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                rfidModel.scanData.value = null

                if (mViewModel.state.get().equals(getString(R.string.stop))){
                    rfidModel.isOpen.value = false
                    mViewModel.state.set(getString(R.string.start))
                }
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listBean.observe(viewLifecycleOwner, Observer {
            loadsir.showSuccess()
            adapter.setList(it)
            adapter!!.appendList(it)
        })
        //扫码
        eventViewModel.zkingType.observeInFragment(this, Observer {
            if (it.Type == STOCK_EPC_ORDER_TYPE){
                assetModel.epcData.value = RfidStateBean(
                    tagId = it.text,
                    scanStatus = SCAN_STATUS_QRCODE,
                    rssi = "0")
            }
        })
        //手柄扫描
        rfidModel.scanData.observe(viewLifecycleOwner, { it ->
            if (it != null && viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                assetModel.epcData.value = RfidStateBean(
                    tagId = it,
                    scanStatus = SCAN_STATUS_SCAN,
                    rssi = "0")
            }
        })
        assetModel.epcData.observe(viewLifecycleOwner, {
            if (it == null) return@observe
            lock.lock()
            try {
                val tagId = it.tagId
                mViewModel.viewModelScope.launch(Dispatchers.IO) {
                    adapter.mFilterList.find { tagId?.contains(it.LabelTag!!, ignoreCase = true) == true}?.apply {
                        var epcAllList = mViewModel.stockEpcDao.findAll(this.RoNo!!, code)
                        if (this.LabelTagNum != epcAllList.size){
                            var find = mViewModel.stockEpcDao.find(this.RoNo!!, tagId!!, code)
                            if (find == null){
                                find = StockEpcBean()
                                find.RoNo = this.RoNo
                                find.createTime = TimeUtils.getNowString()
                                find.epc = tagId
                                find.OrderNo = mViewModel.orderId.get()
                                find.code = code
                                find.LabelTagFirst = this.LabelTag
                                mViewModel.stockEpcDao.add(find)

                                eventViewModel.playMusic.postValue(true)
                                //更新item
                                epcAllList = mViewModel.stockEpcDao.findAll(this.RoNo!!, code)
                                this.ScanNum = epcAllList.size
                                adapter.setData(adapter.mFilterList.indexOf(this), this)
                            }
                        }
                    }
                }
            }finally {
                lock.unlock()
            }
        })
        mViewModel.isShowDialog.observe(viewLifecycleOwner, {
            if (it){
                showLoading(getString(R.string.text1))
            }else{
                dismissLoading()
            }
        })
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        //设置界面 加载中
        loadsir.showEmpty()
        mViewModel.onRequest(mViewModel.orderId.get(), mViewModel.code.get())
    }

    inner class ProxyClick() {

        fun state(){
            if (adapter.mFilterList.size == 0)return
            if (mViewModel.state.get().equals(getString(R.string.start))){
                mViewModel.state.set(getString(R.string.stop))
                rfidModel.isOpen.value = true
            }else{
                mViewModel.state.set(getString(R.string.start))
                rfidModel.isOpen.value = false
            }
        }
        fun save(){
            if (adapter.mFilterList.size == 0)return
            if (mViewModel.state.get().equals(getString(R.string.stop))){
                rfidModel.isOpen.value = false
                mViewModel.state.set(getString(R.string.start))
            }
            mViewModel.onSave(mViewModel.orderId.get(), this@TaskStockListFrg, mViewModel.code.get())
        }
    }


}